package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public int insert(User record) {
        return userMapper.insert(record);
    }

    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    public void register(User user) {

        User registerEmail = userMapper.selectByEmailOrPassword(user.getEmail(), null);
        if (registerEmail != null) {
            //如果不为空,提示用户该邮箱已注册
            throw new RuntimeException("该邮箱已注册");
        }
        user.setHeadImgUrl("/img/user/head.jpg");
        user.setCoverImgUrl("/img/user/bg.jpeg");
        user.setGender(1);
        //保存数据
        userMapper.insert(user);
    }

    /**
     * 登录账号
     *
     * @param email
     * @param password
     * @return
     */
    public User login(String email, String password) {

        User user = userMapper.selectByEmailOrPassword(email, password);
        if (user == null) {
            throw new RuntimeException("亲,您的账号和密码不匹配");
        }
        UserContext.setUser(user);
        return user;
    }

    //分页
    public PageInfo<User> queryUserInfo(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> users = userMapper.selectForList(qo);
        return new PageInfo<User>(users);
    }

}
